package jrain.fw.http.fileupload;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import jrain.fw.core.business.BusinessConst;
import jrain.fw.core.business.BusinessRequest;
import jrain.fw.core.log.Logger;
import jrain.fw.core.log.LoggerFactory;
import jrain.fw.core.utils.FwUtils;
import jrain.utils.exception.ServiceException;
import jrain.utils.lang.StringUtils;

public class FileUploadUitls {

	private static final Logger logger = LoggerFactory.getLogger(FileUploadUitls.class);

	// ===============================================================================================

	public static void parseRquest(BusinessRequest request) {
		try {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload diskFileUpload = new ServletFileUpload(factory);
			HttpServletRequest httpRequest = (HttpServletRequest) request.getExtData(BusinessConst.EXT_REQUEST);
			List<FileItem> list = diskFileUpload.parseRequest((HttpServletRequest) httpRequest);
			List<FileItem> files = new ArrayList<>();
			// 表单字段
			final Map<String, Object> formData = new HashMap<>();
			for (FileItem fileItem : list) {
				if (fileItem.isFormField()) {
					String fieldName = fileItem.getFieldName();
					formData.put(fieldName, fileItem.getString("UTF-8"));
				} else {
					files.add(fileItem);
				}
			}
			// 解析需要的参数
			String paramType = StringUtils.trimNull(formData.get(BusinessConst.REQ_PARAM_TYPE));
			String params = StringUtils.trimNull(formData.get(BusinessConst.REQ_PARAMS));
			// 普通参数
			if (StringUtils.isEmpty(paramType)) {
				// 默认参数类型
				if (!StringUtils.isEmpty(params)) {
					Map<String, Object> dataMap = FwUtils.getJsonService().toMap(params);
					request.setData(dataMap);
				} else {
					Set<String> keySets = formData.keySet();
					for (String key : keySets) {
						request.putData(key, formData.get(key));
					}
				}
			} else if (paramType.startsWith(BusinessConst.REQ_PARAM_PRE)) {
				// 前缀参数类型
				String preData = paramType.substring(4);
				int preDataLength = preData.length() + 1;
				Set<String> names = formData.keySet();
				for (String name : names) {
					if (name.startsWith(preData + "_") && name.length() >= preDataLength) {
						String key = name.substring(preDataLength);
						Object value = formData.get(name);
						request.putData(key, value);
					}
				}
			}
			request.putExtData(BusinessConst.EXT_FILES, files);
		} catch (Exception e) {
			logger.error(request, e.getMessage(), e);
			throw new ServiceException(e.getMessage(), e);
		}
	}

	public static FileItem getFileItem(BusinessRequest request, String fieldName) {
		@SuppressWarnings("unchecked")
		List<FileItem> list = (List<FileItem>) request.getExtData(BusinessConst.EXT_FILES);
		for (FileItem fileItem : list) {
			if (fieldName.equals(fileItem.getFieldName())) {
				return fileItem;
			}
		}
		return null;
	}

}
